package com.zhj.process.config;

import com.zhj.process.util.JacksonUtils;

import org.jetbrains.annotations.NotNull;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 统一包装返回结果，只转换指定包路径下的返回结果，否者会影响swagger
 */
@RestControllerAdvice(basePackages = "com.zhj.process.controller")
public class GlobalResultAdvice implements ResponseBodyAdvice<Object> {
    /**
     * Supports
     *
     * @param returnType    return type
     * @param converterType converter type
     * @return the boolean
     * @since 1.0.0
     */
    @Override
    public boolean supports(@NotNull MethodParameter returnType, @NotNull Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    /**
     * Before body write
     *
     * @param body               o
     * @param methodParameter    method parameter
     * @param mediaType          media type
     * @param aClass             a class
     * @param serverHttpRequest  server http request
     * @param serverHttpResponse server http response
     * @return the object
     * @since 1.0.0
     */
    @Override
    public Object beforeBodyWrite(Object body,
                                  @NotNull MethodParameter methodParameter,
                                  @NotNull MediaType mediaType,
                                  @NotNull Class<? extends HttpMessageConverter<?>> aClass,
                                  @NotNull ServerHttpRequest serverHttpRequest,
                                  @NotNull ServerHttpResponse serverHttpResponse) {
        return  this.warp(body);
    }

    /**
     * Warp
     *
     * @param body body
     * @return the object
     * @since 1.0.0
     */
    private Object warp(Object body) {
        if (body instanceof Result) {
            return body;
        }
        Result<Object> result = Result.success(body);
        if (body instanceof String) {
            return JacksonUtils.toJson(result);
        }
        return result;
    }
}
